#! /usr/bin/env python
# (c) Robert P Krawczyk 2010
# This program is protected by the GPL v3, see the file "COPYING".

import glob,os,re,rrdtool,sys,tempfile
#from Tix import *
from Tkinter import *
import tkFileDialog,tkMessageBox
from PIL import Image,ImageTk

rx_datasource=re.compile("ds\\[([a-zA-Z_]+)\\]")
rx_rra=re.compile("rra.*cf")
CANVAS_WIDTH=800
CANVAS_HEIGHT=300

colors=["#ff0000","#00ff00","#0000ff","#ffff00","#ff00ff","#00ffff","#000000","#444444","#888888","#cccccc"]

class BrowseRRD:
    def __init__(self,root,fname):
        rrdinfo=rrdtool.info(fname)
        #datasources=set(rrdinfo['ds'].keys())
        self.datasources=set(j.group(1) for j in filter(lambda x: x, (rx_datasource.match(j) for j in rrdinfo.keys())))
        #cfs=set(i['cf'] for i in rrdinfo['rra'])
        self.cfs=set(rrdinfo[j] for j in rrdinfo.keys() if rx_rra.match(j))
        self.fname=fname
        self.toplevel=Toplevel(root)
        self.toplevel.title(fname.split('/')[-1])
        self.tempfile=tempfile.NamedTemporaryFile(suffix='.png')
        self.canvas=Canvas(self.toplevel,width=CANVAS_WIDTH*1.2,height=CANVAS_HEIGHT*1.4)
        self.canvas.bind("<Button>",self.event)
        self.canvas.pack()
        f=Frame(self.toplevel)
        Label(f,text="Start time:").pack(side=LEFT)
        self.starttime=Entry(f)
        self.starttime.bind("<Return>",self.drawit)
        self.starttime.pack(side=LEFT)
        #f.pack()
        #f=Frame(self.toplevel)
        Label(f,text="End time:").pack(side=LEFT)
        self.endtime=Entry(f)
        self.endtime.bind("<Return>",self.drawit)
        self.endtime.pack(side=LEFT)
        f.pack()
        self.is_log=IntVar()
        Checkbutton(self.toplevel,text="Logarithmic scale",variable=self.is_log,command=self.drawit).pack()
        Button(self.toplevel,text="Redraw",command=self.drawit).pack()
        self.drawit()

    def drawit(self,event=None):
        args=[self.tempfile.name,'-w %d'%CANVAS_WIDTH,'-h %d'%CANVAS_HEIGHT]
        if self.is_log.get():
            args.append('-o')
        starttime=self.starttime.get()
        if starttime!='':
            args.append('-s %s'%starttime)
        endtime=self.endtime.get()
        if endtime!='':
            args.append('-e %s'%endtime)
        colnum=0
        for ds in self.datasources:
            for cf in self.cfs:
                args.append('DEF:%s_%s=%s:%s:%s'%(ds,cf,self.fname,ds,cf))
                args.append('LINE1:%s_%s%s:"%s %s"'%(ds,cf,colors[colnum%len(colors)],ds,cf))
                colnum+=1
        try:
            rrd_return=rrdtool.graph(*args)
        except Exception,excp:
            tkMessageBox.showerror("Error generating chart!",str(excp))
            return
        print "graph =",rrd_return
        #rrdtool.graph('/tmp/g.png','-o','DEF:used_avg=%s:used:AVERAGE'%fname,'LINE1:used_avg#ff0000:used')
        self.canvas['width']=rrd_return[0]
        self.canvas['height']=rrd_return[1]
        self.img=ImageTk.PhotoImage(Image.open(self.tempfile.name))
        try:
            self.canvas.itemconfig(self.image_id,image=self.img)
        except AttributeError:
            self.image_id=self.canvas.create_image(0,0,image=self.img,anchor=NW)
            print "create image =",self.image_id

    def event(self,event):
        print event.type,event.num
        x=self.canvas.canvasx(event.x)
        y=self.canvas.canvasx(event.y)
        if event.num==1:
            self.canvas.create_oval(x-7,y-7,x+7,y+7)
        elif event.num==2:
            self.canvas.create_oval(x-7,y-7,x+7,y+7,outline="red")
        elif event.num==3:
            self.canvas.create_oval(x-7,y-7,x+7,y+7,outline="green")
            


def openfile():
    fname=tkFileDialog.askopenfilename(initialdir=mydir,filetypes=[('RRD','*.rrd'),('all','*')])
    tl=BrowseRRD(root,fname)


def changedir():
    global mydir
    mydir=tkFileDialog.askdirectory(initialdir=mydir)
    dirlabel['text']="Current directory: '%s'"%mydir

try:
    mydir=sys.argv[1]
except IndexError:
    mydir='.'
print mydir
root=Tk()
root.title("RRD inspect")
Label(root,text="Tool for inspecting rrd files").pack()
dirlabel=Label(root,text="Current directory: '%s'"%mydir)
dirlabel.pack()
f=Frame(root)
Button(f,text="Open File",command=openfile).pack(side=LEFT)
Button(f,text="Change directory",command=changedir).pack(side=LEFT,padx=10)
f.pack()
root.mainloop()
